package com.example.demo.grbkxt.servlet;

import com.example.demo.grbkxt.mapper.SettingsMapper;
import com.example.demo.grbkxt.model.Settings;
import com.example.demo.grbkxt.util.MyBatisUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.UUID;

@WebServlet("/admin/settings")
public class AdminSettingsServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try (SqlSession session = MyBatisUtil.openSession()) {
            SettingsMapper mapper = session.getMapper(SettingsMapper.class);
            Settings settings = mapper.getSettings();
            if (settings == null) {
                settings = new Settings(); // 使用默认值
            }
            request.setAttribute("settings", settings);
            request.getRequestDispatcher("/WEB-INF/views/admin/settings.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try (SqlSession session = MyBatisUtil.openSession()) {
            SettingsMapper mapper = session.getMapper(SettingsMapper.class);
            Settings settings = mapper.getSettings();
            boolean isNew = (settings == null);

            if (isNew) {
                settings = new Settings();
                settings.setId(UUID.randomUUID().toString());
            }

            settings.setSiteTitle(request.getParameter("siteTitle"));
            settings.setSiteDescription(request.getParameter("siteDescription"));
            settings.setPostsPerPage(Integer.parseInt(request.getParameter("postsPerPage")));
            settings.setAllowComments("on".equals(request.getParameter("allowComments")));
            settings.setAllowRegistration("on".equals(request.getParameter("allowRegistration")));

            if (isNew) {
                mapper.insertSettings(settings);
            } else {
                mapper.updateSettings(settings);
            }

            session.commit();
            response.sendRedirect(request.getContextPath() + "/admin/settings");
        }
    }
}
